<template>
  <div>
    <h1>用户管理</h1>
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="关键字">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入关键字"
            clearable
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            v-model="searchForm.gender"
            placeholder="请选择性别"
            style="width: 150px"
            clearable
          >
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="起始时间">
          <el-date-picker
            v-model="searchForm.beginTime"
            type="datetime"
            placeholder="请选择起始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="searchForm.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadList">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-button type="danger" @click="onDeleteAllUser">批量删除</el-button>
    <div>
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userId" label="用户ID" />
        <el-table-column prop="userName" label="登录账号" />
        <el-table-column prop="nickName" label="真实姓名" />
        <el-table-column prop="gender" label="性别">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.gender == 0">男</el-tag>
            <el-tag type="danger" v-if="scope.row.gender == 1">女</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userMobile" label="手机号" />
        <el-table-column prop="userEmail" label="邮箱" />
        <el-table-column prop="userAvatar" label="头像">
          <template #default="scope">
            <el-image
              :src="scope.row.userAvatar"
              style="width: 100px; height: 100px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="ontoUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="onDeleteUser(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-pagination
        style="margin-top: 30px"
        v-model:current-page="searchForm.pageNum"
        v-model:page-size="searchForm.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" title="用户编辑" width="500">
        <el-form :model="form">
          <el-form-item label="真实姓名" :label-width="formLabelWidth">
            <el-input v-model="form.nickName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="登录账号" :label-width="formLabelWidth">
            <el-input v-model="form.userName" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="手机号" :label-width="formLabelWidth">
            <el-input v-model="form.userMobile" autocomplete="off" />
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth">
            <el-input v-model="form.userMobile" autocomplete="off" />
          </el-form-item>
          <el-form-item label="性别" :label-width="formLabelWidth">
            <el-select v-model="form.gender" placeholder="请选择性别">
              <el-option label="男" :value="0" />
              <el-option label="女" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="头像" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/user/index/uploadFile"
              :show-file-list="false"
              :headers="headers"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="onupdateUser"> 保存 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { getUserList, updateUser, deleteUser, deleteAllUser } from "../api/api";
import { tr } from "element-plus/es/locales.mjs";
import { ElMessage, ElMessageBox, type UploadProps } from "element-plus";

const multipleSelection = ref<any[]>([]);
const headers = ref({ token: sessionStorage.getItem("token") });
const imageUrl = ref("");
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const tableData = ref([]);
const total = ref(0);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: null,
  gender: null,
  beginTime: null,
  endTime: null,
});
const form = ref({
  createTime: null,
  gender: null,
  nickName: null,
  reason: null,
  token: null,
  userAvatar: "",
  userEmail: null,
  userId: null,
  userMobile: null,
  userName: null,
  userPass: null,
  userStatus: null,
});
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  //imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  form.value.userAvatar = response.data;
  imageUrl.value = form.value.userAvatar;
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadList();
};
//编辑打开弹框
const ontoUpdate = (row: any) => {
  Object.assign(form.value, row);
  imageUrl.value = row.userAvatar;
  dialogFormVisible.value = true;
};
//编辑
const onupdateUser = () => {
  updateUser(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("修改成功");
      dialogFormVisible.value = false;
      loadList();
    } else {
      ElMessage.error("修改失败");
    }
  });
};
//删除
const onDeleteUser = (row: any) => {
  ElMessageBox.confirm("删除后数据不可恢复，确定删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteUser(row.userId).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {});
};
//批量删除
const onDeleteAllUser = () => {
  ElMessageBox.confirm("删除后数据不可恢复，确定删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteAllUser(multipleSelection.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {});
};
const loadList = () => {
  getUserList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};
//页面加载钩子函数
onMounted(() => {
  loadList();
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
